<template>
  <div class="app-container">
    <el-button
      type="primary"
      icon="el-icon-circle-plus"
      round
      size="mini"
      class="add-btn"
      @click="$router.push('/system/add_user')"
      >添加用户</el-button
    >
    <el-table
      v-loading="listLoading"
      :data="usersInfo.records"
      element-loading-text="加载中......"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="用户名" prop="username" />
      <el-table-column label="昵称" prop="nickname" />
      <el-table-column label="邮箱" prop="email" />
      <el-table-column label="头像" align="center">
        <template slot-scope="scope">
          <el-image
            :src="scope.row.avatar"
            fit="cover"
            style="width: 50px; height: 50px"
          />
        </template>
      </el-table-column>
      <el-table-column label="性别" prop="gender" width="60" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.gender | genderFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话" prop="phone" />
      <el-table-column label="状态" width="110" align="center">
        <template slot-scope="scope">
          <el-tag
            size="mini"
            effect="dark"
            :type="scope.row.status | statusFilter"
          >
            {{ scope.row.status === 1 ? "禁用" : "正常" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template slot-scope="scope"
          ><i class="el-icon-time" /> {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-view"
            @click="showRoles(scope.row.id)"
            >角色
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-circle-plus-outline"
            @click="showAddRoles(scope.row.id)"
            >赋权
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-delete"
            @click="showDelUser(scope.row.id)"
            >删除
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="
              $router.push({
                path: '/system/mod_user',
                query: { userId: scope.row.id },
              })
            "
            >修改</el-link
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :hide-on-single-page="true"
      :current-page="usersInfo.current"
      :page-size="usersInfo.size"
      layout="total, prev, pager, next, jumper"
      :total="usersInfo.total"
      @current-change="handleUserPageChange"
    />

    <!-- 角色展示弹出框 -->
    <el-dialog title="角色列表" :visible.sync="rolesVisible" width="40%">
      <el-table :data="roles">
        <el-table-column property="roleName" label="角色" width="150" />
        <el-table-column property="roleKey" label="关键字" />
        <el-table-column property="createTime" label="创建时间" />
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-link type="primary" @click="handleDelUserRole(scope.row.id)"
              >移除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 用于赋予角色弹出框 -->
    <el-dialog
      title="给用户赋予角色"
      :visible.sync="addRolesVisible"
      width="40%"
    >
      <el-table :data="allRolesPage.records">
        <el-table-column property="roleName" label="角色" width="150" />
        <el-table-column property="roleKey" label="关键字" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              :disabled="
                !!roles.find((ele) => {
                  return ele.id === scope.row.id;
                })
              "
              type="primary"
              plain
              size="mini"
              icon="el-icon-circle-plus-outline"
              @click="handleAddUserRole(scope.row.id)"
              >赋权
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :hide-on-single-page="true"
        :current-page="allRolesPage.current"
        :page-size="allRolesPage.size"
        layout="total, prev, pager, next, jumper"
        :total="allRolesPage.total"
        @current-change="handleRolesPageChange"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserList,
  getRoleListByUserId,
  getRoleList,
  insertUserRole,
  delUserRole,
  delUserById,
} from "@/api/system";

export default {
  filters: {
    statusFilter(status) {
      const statusList = ["success", "info"];
      return statusList[status];
    },
    genderFilter(gender) {
      const statusList = ["男", "女", "保密"];
      return statusList[gender];
    },
  },
  data() {
    return {
      usersInfo: { size: 10, current: 1, total: 0, records: [] },
      listLoading: true,
      rolesVisible: false,
      addRolesVisible: false,
      allRolesPage: { size: 10, current: 1, total: 0, records: [] },
      roles: [],
      currentUserId: null,
    };
  },
  created() {
    this.fetchUsersPage();
  },
  methods: {
    fetchUsersPage() {
      this.listLoading = true;
      getUserList({
        page: this.usersInfo.current,
        limit: this.usersInfo.size,
      }).then((response) => {
        this.usersInfo = response.data;
        this.listLoading = false;
      });
    },
    fetchAllRolesByUserId() {
      getRoleListByUserId(this.currentUserId).then((res) => {
        this.roles = res.data;
      });
    },
    fetchRolesPage() {
      getRoleList({
        page: this.allRolesPage.current,
        limit: this.allRolesPage.size,
      }).then((res) => {
        this.allRolesPage = res.data;
      });
    },
    handleUserPageChange(page) {
      this.usersInfo.current = page;
      this.fetchUsersPage();
    },
    showRoles(userId) {
      this.rolesVisible = true;
      this.currentUserId = userId;
      this.fetchAllRolesByUserId();
    },
    showAddRoles(userId) {
      this.addRolesVisible = true;
      this.currentUserId = userId;
      this.fetchAllRolesByUserId();
      this.fetchRolesPage();
    },
    handleDelUserRole(roleId) {
      delUserRole({
        userId: this.currentUserId,
        roleId: roleId,
      }).then((res) => {
        this.$notify.success({
          title: "提示",
          message: res.message,
        });
      });
      this.rolesVisible = false;
    },
    handleAddUserRole(roleId) {
      insertUserRole({
        userId: this.currentUserId,
        roleId: roleId,
      }).then((res) => {
        this.$notify.success({
          title: "提示",
          message: res.message,
        });
      });
      this.addRolesVisible = false;
    },
    handleRolesPageChange(page) {
      this.allRolesPage.current = page;
      this.fetchRolesPage();
    },
    showDelUser(userId) {
      this.$confirm("确认删除该用户？删除之后不可恢复")
        .then((val) => {
          delUserById(userId).then((_) => {
            this.$notify.success({
              title: "提示",
              message: "用户删除成功",
            });
            this.fetchUsersPage();
          });
        })
        .catch((_) => {});
    },
  },
};
</script>

<style scoped>
.add-btn {
  margin-bottom: 10px;
}
.el-link {
  font-size: 12px;
  margin-left: 4px;
}
.el-link:hover {
  font-weight: bold;
}
</style>
